package cn.tedu._03vehicle.base.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
public class RataLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_REQUESTS_COUNT=3;
    private static final int WINDOW_SIZE_SECONDS=60;
    private  final ConcurrentHashMap<String,Integer> clientCounts=new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, LocalDateTime> lastResetTimes=
            new ConcurrentHashMap<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          log.debug("进入网站限流拦截器....");
          //获取客户端的IP地址
        String addr = request.getRemoteAddr();
        //获取最后一次访问的时间
        LocalDateTime latresetTime = lastResetTimes.get(addr);
        if (latresetTime==null||LocalDateTime.now().isAfter
                (latresetTime.plusSeconds(WINDOW_SIZE_SECONDS))){
            clientCounts.put(addr,0);
            lastResetTimes.put(addr,LocalDateTime.now());

        }
        //计数器+1
        Integer i=clientCounts.merge(addr,1,Integer::sum);
        if (i>3){
            throw new RuntimeException("访问过于频繁，请稍后再试");
        }
        return true;

    }
}
